package com.zjmzxfzhl.modules.flowable.service.impl;

import com.zjmzxfzhl.common.core.exception.BaseException;
import com.zjmzxfzhl.modules.flowable.entity.FlowableForm;
import com.zjmzxfzhl.modules.flowable.mapper.FlowableFormMapper;
import com.zjmzxfzhl.modules.flowable.service.ClientService;
import io.dshubs.archives.dto.ArchiveBaseCategoryDto;
import io.dshubs.archives.feign.ArchivesFeignClient;
import io.dshubs.commons.tools.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.alibaba.fastjson.JSON.parseArray;
import static com.alibaba.fastjson.JSON.parseObject;

/**
 * @author tan 2021/9/7
 **/
@Service
public class ClientServiceImpl implements ClientService {


    @Autowired
    private ArchivesFeignClient archivesFeignClient;

    @Autowired
    private FlowableFormMapper flowableFormMapper;

    @Override
    public List<Map<String,String>> getClassField(Long id){

        Result<ArchiveBaseCategoryDto> archiveBaseCategoryDtoResult = archivesFeignClient.getById(id);
        ArchiveBaseCategoryDto categoryDtoResult = archiveBaseCategoryDtoResult.getData();
        if(categoryDtoResult == null) {
            return null;
        }
        FlowableForm flowableForm = flowableFormMapper.selectById(categoryDtoResult.getFormKey());
        if(flowableForm == null) {
            return null;
        }
        String formJson = flowableForm.getFormJson();
        return analysisJson(formJson);
    }

    private List<Map<String,String>>  analysisJson(String formJson){
        List<Map<String,String>> resList = new ArrayList<>();
        Map formMap = parseObject(formJson,Map.class);
        Object[] fields = parseArray(formMap.get("fields").toString()).toArray();
        for (Object fieldObj : fields) {
            String fieldStrJson = String.valueOf(fieldObj);
            Map map = parseObject(fieldStrJson, Map.class);
            Map<String,String> resMap = new HashMap<>(16);
            resMap.put("__vModel__",String.valueOf(map.get("__vModel__")));
            String config__ = String.valueOf(map.get("__config__"));
            Map configMap = parseObject(config__, Map.class);
            resMap.put("label",String.valueOf(configMap.get("label")));
            resList.add(resMap);
        }
        return resList;
    }
}
